import java.time.LocalDate;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/api/card")
public class CardController {

    // 模拟数据库存储，实际应用中替换为真实数据库操作
    private static Map<String, CardInfo> cardDB = new ConcurrentHashMap<>();
    private static Map<String, String> macToCardMap = new ConcurrentHashMap<>();
    private static CardController cardController = null;

    /**
     * 登录接口
     * @param request 包含卡号和mac地址的请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseEntity<ApiResponse> login(@RequestBody LoginRequest request) {

            String cardNumber = request.getCardNumber();
            String macAddress = request.getMacAddress();

            // 1. 检查卡号是否存在
            if (!cardDB.containsKey(cardNumber)) {
                return ResponseEntity.ok(ApiResponse.error("卡号不存在"));
            }

            CardInfo cardInfo = cardDB.get(cardNumber);

            // 2. 检查卡号是否已过期
            if (cardInfo.getExpiryDate().isBefore(LocalDate.now())) {
                return ResponseEntity.ok(ApiResponse.error("卡号已过期"));
            }
            // 3. 检查该MAC是否已绑定其他卡号
            if (macToCardMap.containsKey(macAddress) &&
                    !macToCardMap.get(macAddress).equals(cardNumber)) {
                return ResponseEntity.ok(ApiResponse.error("该设备已绑定其他卡号"));
            }
            // 4. 检查绑定状态
            String boundMac = cardInfo.getBoundMacAddress();
            if(cardController==null){
                synchronized (CardController.class) {
                    if (cardController == null) {
                        cardController = new CardController();
                    }
                    try {
                        if (boundMac == null) {
                            // 卡号未绑定，进行绑定
                            cardInfo.setBoundMacAddress(macAddress);
                            macToCardMap.put(cardNumber, macAddress);
                            return ResponseEntity.ok(ApiResponse.success("登录并绑定成功",
                                    Map.of("expiryDate", cardInfo.getExpiryDate())));
                        } else if (boundMac.equals(macAddress)) {
                            // 已绑定当前机器，允许登录
                            return ResponseEntity.ok(ApiResponse.success("登录成功",
                                    Map.of("expiryDate", cardInfo.getExpiryDate())));
                        } else {
                            // 已绑定其他机器，拒绝登录
                            return ResponseEntity.ok(ApiResponse.error("卡号已绑定其他设备，请先解绑"));
                        }
                    } catch (Exception e) {
                        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                .body(ApiResponse.error("系统错误: " + e.getMessage()));
                    }
                }
                 }
               }
            }


    // 其他接口方法（生成、解绑、查询）...
}

// 请求对象
class LoginRequest {
    private String cardNumber;
    private String macAddress;

    // getters and setters
    public String getCardNumber() {
        return cardNumber;
    }

    public void setCardNumber(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    public String getMacAddress() {
        return macAddress;
    }

    public void setMacAddress(String macAddress) {
        this.macAddress = macAddress;
    }
}

// 卡号信息类
class CardInfo {
    private String cardNumber;
    private LocalDate createDate;
    private LocalDate expiryDate;
    private String boundMacAddress;

    // 构造函数
    public CardInfo(String cardNumber) {
        this.cardNumber = cardNumber;
        this.createDate = LocalDate.now();
        this.expiryDate = this.createDate.plusMonths(6);
    }

    // getters and setters
    public String getCardNumber() {
        return cardNumber;
    }

    public LocalDate getCreateDate() {
        return createDate;
    }

    public LocalDate getExpiryDate() {
        return expiryDate;
    }

    public String getBoundMacAddress() {
        return boundMacAddress;
    }

    public void setBoundMacAddress(String boundMacAddress) {
        this.boundMacAddress = boundMacAddress;
    }
}

// 统一API响应格式
class ApiResponse {
    private boolean success;
    private String message;
    private Object data;

    // 静态工厂方法
    public static ApiResponse success(String message, Object data) {
        return new ApiResponse(true, message, data);
    }

    public static ApiResponse error(String message) {
        return new ApiResponse(false, message, null);
    }

    // 构造函数
    public ApiResponse(boolean success, String message, Object data) {
        this.success = success;
        this.message = message;
        this.data = data;
    }

    // getters
    public boolean isSuccess() {
        return success;
    }

    public String getMessage() {
        return message;
    }

    public Object getData() {
        return data;
    }
}